/*
 * Copyright(c) 2024 长沙市希尚网络科技有限公司
 * 注意：本内容仅限于长沙市希尚网络科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */

package org.example.security.core;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * TODO
 *
 * @author liuy
 * @version 1.0 2024/11/15 0015
 */
@Component
public class TokenPreFilter extends OncePerRequestFilter {
    public static final HashMap<String,Authentication> tokenMap = new HashMap();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");

        if (StrUtil.isNotBlank(authorizationHeader)) {
            // 获取 Token
            // String token = authorizationHeader.substring(7);

            // 这里可以调用你的 JWT 工具类来验证 Token
            // 例如：
            // if (jwtTokenUtil.validateToken(token)) {
            //     UserDetails userDetails = userDetailsService.loadUserByUsername(jwtTokenUtil.getUsernameFromToken(token));
            //     UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            //             userDetails, null, userDetails.getAuthorities());
            //     authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //     SecurityContextHolder.getContext().setAuthentication(authentication);
            // }
            // Authentication authentication = tokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(tokenMap.get(authorizationHeader));
            // 直接放行携带 Token 的请求
            chain.doFilter(request, response);
        } else {
            // 不携带 Token 的请求继续进行安全检查
            chain.doFilter(request, response);
        }
    }
}
